<template>
  <view class="container">
    <template v-if="Rejected || Fulfilled">
      <view v-if="Fulfilled" class="pay-result success">
        <image src="/static/images/success.png" mode="widthFix" />
        <view class="result-title">支付成功</view>
        <view class="result-count">
          将于 <text style="color: #3072f6">{{ count }}s</text> 后自动返回上一页，并刷新页面
        </view>
      </view>

      <view v-if="Rejected" class="pay-result cancel">
        <image src="/static/images/error.png" mode="widthFix" />
        <view class="result-title">支付失败，账单已取消</view>
        <view class="result-count">
          将于 <text style="color: #3072f6">{{ count }}s</text> 后自动返回上一页，并刷新页面
        </view>
      </view>
    </template>
    <template
      v-else-if="
        options.from == 'asset/asset-fee/list_cancel' ||
        options.from == 'order/short-order/detail/index_cancel' ||
        options.from == 'order/long-order/detail/index_cancel'
      "
    >
      <view class="cancel-payment">
        <view>当前费用关联了合并确认的三方支付账单，</view>
        <view>请确认是否取消账单下所有费用的收付款？</view>
      </view>
    </template>
    <template v-else>
      <view class="tip">
        请于 <text class="time"> {{ details.expireTime }} </text> 前完成账单的支付，否则账单会自动取消
      </view>
      <view class="title">嘉联聚合支付</view>
      <view class="qrcode">
        <uqrcode v-if="details.scanQrCode" ref="uqrcode" canvas-id="qrcode" :value="details.scanQrCode" />
      </view>
      <view class="img-box">
        <image src="/static/images/yunshanfu.png" mode="widthFix" />
        <image src="/static/images/zhifubao.png" mode="widthFix" />
        <image src="/static/images/weixin.png" mode="widthFix" />
      </view>
    </template>

    <ve-card :sub-title="payCardResult" :type="payCardType" fold="true" v-model:initFold="initExpand">
      <template #title>
        <view class="title-box">
          <view class="title-item">
            <text class="title-label"> 账单号 </text>
            <text class="title-value"> {{ details.billCode }} </text>
          </view>
          <view class="title-item">
            <text class="title-label"> 外部账单号 </text>
            <text class="title-value"> {{ details.outBillCode }} </text>
          </view>
        </view>
      </template>

      <ve-cell label="费用明细">
        <view>
          <view style="margin-bottom: 5px" v-for="item in details.feeList" :key="item.id">
            {{ item.feeName }}: {{ unitVal(item.feeActiveAmount) }}
          </view>
        </view>
      </ve-cell>
      <ve-cell-price label="账单金额" :value="details.totalAmount" />
      <ve-cell label="客户名称">{{ details.customerName }}</ve-cell>
      <ve-cell label="费用备注">{{ details.remark }}</ve-cell>
      <ve-cell label="操作人">{{ details.createUserName }}</ve-cell>
      <ve-cell label="账单生成时间">{{ details.createTime }}</ve-cell>
    </ve-card>

    <ve-bottom-box
      size="mini"
      v-if="
        options.from == 'asset/asset-fee/list_cancel' ||
        options.from == 'order/short-order/detail/index_cancel' ||
        options.from == 'order/long-order/detail/index_cancel'
      "
    >
      <ve-button type="primary" size="large" block @click="cancelPayment" :loading="cancelPaymentLoading">确认取消</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { unitVal } from '@/utils'
  import { getBillQrCode, getPayResult, getQrCode, cancelPay } from '@/api/common'
  import { onBackPress, onLoad, onUnload } from '@dcloudio/uni-app'

  const payCardResult = ref('未支付')
  const payCardType = ref('yellow')
  const options = ref<any>({})
  const details = ref<any>([])
  const initExpand = ref(true)

  // 设置支付标题的页面
  const SET_PAYMENT_TITLE_ARRAY = [
    'asset/asset-fee/confirm-fee',
    'asset/asset-fee/list',
    'order/short-order/detail/confirmExpenses',
    'order/long-order/detail/confirmExpenses',
    'order/short-order/detail/index',
    'order/long-order/detail/index',
  ]
  const CANCELPAYMENT_ARRAY = [
    'asset/asset-fee/list_cancel',
    'order/short-order/detail/index_cancel',
    'order/long-order/detail/index_cancel',
  ]
  // ------------------------------------------------------------

  // 确认费用跳转到收款码页面 返回2次
  const COMFIRMPAY_ARRAY = [
    'asset/asset-fee/confirm-fee',
    'order/short-order/detail/confirmExpenses',
    'order/long-order/detail/confirmExpenses',
  ]
  // 从费用信息列表跳转到收款码页面 返回1次
  const PAYCODE_OR_UNPAYCODE_ARRAY = [
    'asset/asset-fee/list',
    'asset/asset-fee/list_cancel',
    'order/short-order/detail/index',
    'order/short-order/detail/index_cancel',
    'order/long-order/detail/index',
    'order/long-order/detail/index_cancel',
  ]
  // 从合并确认页面跳转到收款码页面 返回3次
  const MERGE_CONFIRM_ARRAY = ['order/short-order/detail/mergeConfirmation', 'order/long-order/detail/mergeConfirmation']

  const TIME_COUNT = 3
  const DELAY = 3000
  const Rejected = ref(false)
  const Fulfilled = ref(false)
  const count = ref(TIME_COUNT)
  let timer: any = null
  let downTimer: any = null

  const countDown = () => {
    if (!downTimer) {
      downTimer = setInterval(() => {
        count.value--
        if (count.value === 0) {
          clearInterval(downTimer)
          downTimer = null

          if (PAYCODE_OR_UNPAYCODE_ARRAY.includes(options.value.from)) {
            uni.navigateBack()
          } else if (MERGE_CONFIRM_ARRAY.includes(options.value.from)) {
            uni.navigateBack({
              delta: 3,
            })
          } else {
            uni.navigateBack({
              delta: 2,
            })
          }

          uni.$emit('refreshData')
        }
      }, 1000)
    }
  }

  const payStatus = (orderSerialNo: string) => {
    return new Promise((resolve) => {
      getPayResult({ orderSerialNo }).then((res: any) => {
        resolve(res.result)
      })
    })
  }

  // 通过轮询获取支付状态
  const pollingPayStatus = (orderSerialNo: string, delay = DELAY) => {
    payStatus(orderSerialNo).then((result: any) => {
      /**
       * 支付成功
       * 1. 停止轮询
       * 2. 倒计时返回页面
       */
      if (result.resultCode == 200) {
        clearTimeout(timer)
        timer = null
        payCardResult.value = '已支付'
        payCardType.value = 'blue'
        Fulfilled.value = true
        countDown()
      } else if (result.resultCode == 300) {
        clearTimeout(timer)
        timer = null
        Rejected.value = true
        countDown()
      } else {
        timer = setTimeout(() => {
          pollingPayStatus(orderSerialNo, delay)
        }, delay)
      }
    })
  }

  // 获取收款二维码
  const getPaymentQrCode = async (options: any) => {
    if (COMFIRMPAY_ARRAY.includes(options.from) || MERGE_CONFIRM_ARRAY.includes(options.from)) {
      const res = await getBillQrCode({ id: options.id })
      details.value = res.result
    } else if (PAYCODE_OR_UNPAYCODE_ARRAY.includes(options.from)) {
      const res = await getQrCode({ feeId: options.id, refId: options.refId, bizType: options.bizType })
      details.value = res.result
    }

    payCardResult.value = details.value.payStatusName

    switch (
      details.value.payStatus // 0: 未支付 1: 已支付 9: 已取消
    ) {
      case 0:
        payCardType.value = 'yellow'
        break
      case 1:
        payCardType.value = 'blue'
        break
      case 9:
        payCardType.value = 'gray'
        break
    }

    /**
     * 获取支付二维码成功
     * 1. 不是取消收款操作
     * 2. 轮询获取支付状态
     */
    if (details.value.scanQrCode && !CANCELPAYMENT_ARRAY.includes(options.from)) {
      pollingPayStatus(details.value.billCode)
    } else {
      payStatus(details.value.billCode).then((result: any) => {
        if (result.resultCode == 200 || result.resultCode == 300) {
          uni.showToast({
            title: `${result.msg}, 将于 3s 后自动返回`,
            duration: 3000,
            icon: 'none',
            mask: true,
          })

          cancelPaymentLoading.value = true

          setTimeout(() => {
            uni.navigateBack()
            uni.$emit('refreshData')
            cancelPaymentLoading.value = false
          }, 3000)
        }
      })
    }
  }

  const cancelPaymentLoading = ref(false)
  // 取消收款
  const cancelPayment = () => {
    cancelPaymentLoading.value = true

    cancelPay({ id: details.value.id })
      .then(() => {
        uni.showToast({
          title: '取消成功',
        })
        uni.navigateBack()
      })
      .finally(() => {
        cancelPaymentLoading.value = false
      })
  }

  onBackPress((query: any) => {
    if (query.from == 'navigateBack') {
      return false
    }

    if (COMFIRMPAY_ARRAY.includes(options.value.from)) {
      uni.navigateBack({
        delta: 2,
      })
    } else if (MERGE_CONFIRM_ARRAY.includes(options.value.from)) {
      uni.navigateBack({
        delta: 3,
      })
    } else {
      uni.navigateBack()
    }
    return true
  })

  onLoad((query: any) => {
    console.log('query', query.from)

    options.value = query
    const { from } = query

    if (SET_PAYMENT_TITLE_ARRAY.includes(from)) {
      uni.setNavigationBarTitle({
        title: '收款码',
      })
    } else if (CANCELPAYMENT_ARRAY.includes(from)) {
      uni.setNavigationBarTitle({
        title: '取消收款',
      })
    }

    getPaymentQrCode(query)
  })

  onUnload(() => {
    console.log('onUnload')
    clearTimeout(timer)
    clearInterval(downTimer)
    timer = null
    downTimer = null
  })
</script>

<style lang="less" scoped>
  .container {
    padding: 24rpx;
  }

  .tip {
    margin-bottom: 24px;
    font-weight: 600;
    font-size: 16px;
    color: #1d2129;
    text-align: center;
    .time {
      color: #3072f6;
    }
  }

  .title {
    font-weight: 500;
    font-size: 18px;
    color: #1d2129;
    text-align: center;
  }

  .qrcode {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 14px;
    margin-bottom: 24px;
  }

  .img-box {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24px;
    image {
      width: 48px;
      height: 48px;
      margin-right: 20px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .title-box {
    display: flex;
    flex-direction: column;
    width: 450rpx;
    font-weight: 400;
    font-size: 12px;
    color: #8491a8;

    .title-item {
      display: flex;
      .title-label {
        display: flex;
        justify-content: flex-end;
        width: 26%;
        margin-right: 5px;
      }
      .title-value {
        width: 73%;
        text-align: left;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .cancel-payment {
    height: 124px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
    color: #f53f3f;
  }

  .pay-result {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 172px;
    font-weight: 400;
    font-size: 12px;
    color: #8491a8;

    image {
      width: 48px;
      height: 48px;
      margin-bottom: 4px;
    }

    .result-title {
      font-weight: 500;
      font-size: 14px;
      color: #1d2129;
      margin-bottom: 6px;
    }
  }
</style>
